import type { AddRouteRecord, MenuRecord } from '@oaexpert/layouts'
import type { Router, RouteRecordRaw } from 'vue-router'
import { SvgIcon } from '@/components/svg-icon'
import Layout from '@/layout/BaseLayout.vue'
import { useAppStoreWithOut, useUserStore } from '@/store'
import { filterRouters, useMenuState } from '@oaexpert/layouts'
import { $t, $te } from '@oaexpert/locales'
import { notification } from 'ant-design-vue'
import { h } from 'vue'

const modules = import.meta.glob('../views/**/*.{vue,tsx}')
export function generateRoutes(routers: AddRouteRecord[]): RouteRecordRaw[] {
  if (!routers?.length) {
    return [{
      path: '/:path(.*)*',
      redirect: '/403',
      name: '403Page',
      meta: { visible: false },
    }]
  }

  const [unChildrenRoutes, childrenRoutes] = routers.reduce<[AddRouteRecord[], AddRouteRecord[]]>(
    ([noChild, hasChild], route) => {
      return route.children?.length
        ? [noChild, [...hasChild, route]]
        : [[...noChild, route], hasChild]
    },
    [[], []],
  )
  const routes = [...childrenRoutes]
  if (unChildrenRoutes.length > 0) {
    routes.push({
      menuPath: '/',
      menuComponent: '/Layout',
      menuName: '_BaseRoot',
      redirect: { name: unChildrenRoutes[0].menuName },
      children: unChildrenRoutes,
    } as AddRouteRecord)
  }
  const addRouters = [
    ...deepRoute(routes),
    {
      path: '/:path(.*)*',
      redirect: '/404',
      name: '404Page',
      meta: { visible: false },
    },
  ]
  if (!addRouters.some(r => r.path === '/')) {
    addRouters.unshift({
      path: '/',
      redirect: {
        name: addRouters[0].name,
      },
    })
  }
  return addRouters
}

export function deepRoute(routers: AddRouteRecord[]): RouteRecordRaw[] {
  return routers.map((route) => {
    const { menuComponent, menuName, menuPath, children, ...meta } = route
    const baseRoute = {
      component: loadView(route),
      path: menuPath,
      name: menuName,
      meta,
    }

    if (!children?.length)
      return baseRoute as RouteRecordRaw

    return {
      ...baseRoute,
      redirect: children[0]?.menuName ? { name: children[0].menuName } : undefined,
      children: deepRoute(children),
    } as RouteRecordRaw
  })
}

export function loadView(route: AddRouteRecord) {
  if (route.menuComponent === '/Layout')
    return Layout

  const paths = [
    `../views${route.menuComponent}.vue`,
    `../views${route.menuComponent}.tsx`,
    `../views${route.menuComponent}/index.vue`,
    `../views${route.menuComponent}/index.tsx`,
  ]
  const comModule = paths.find(path => modules[path])

  if (!comModule) {
    console.error(`组件文件未找到：${route.menuComponent}`)
    return () => import('@/views/Error/404.vue') // 当组件未找到时返回404页面组件
  }

  return modules[comModule]
}
export function filterMenusByVisible(menus: AddRouteRecord[]): MenuRecord[] {
  return menus
    .filter(menu => menu.menuVisible && menu.menuType !== 'button')
    .map(menu => ({
      ...menu,
      menuIcon: h(SvgIcon, { icon: menu.menuIcon }),
      menuTitle: () => {
        const meta = menu?.meta ? menu.meta : { Intl: '' }
        return !meta.Intl || meta.Intl === '' ? menu.menuTitle : $te(meta.Intl) ? $t(meta.Intl) : menu.menuTitle
      },
      children: menu.children ? filterMenusByVisible(menu.children) : undefined,
    }))
    .filter(menu => !menu.children || menu.children.length > 0)
    .sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0))
}

export function useDynamicRouter(router: Router) {
  const { menus, addRouters, resetMenuState } = useMenuState()

  const handleAddRouter = async () => {
    try {
      const userStore = useUserStore()
      const menuList = await userStore.getMenuList()
      // 检查menuList是否为空或无效，防止出现无限循环
      if (!menuList || !Array.isArray(menuList) || menuList.length === 0) {
        console.warn('获取到的菜单列表为空，无法生成路由')
        notification.error({
          message: '错误提示',
          description:
            '当前账号暂无权限访问，请联系系统管理员分配权限',
        })
        return false
      }

      const filterRoutersList = filterRouters(menuList as AddRouteRecord[])

      // 确保过滤后的路由列表不为空
      if (!filterRoutersList || filterRoutersList.length === 0) {
        console.warn('过滤后的路由列表为空，无法生成路由')
        return false
      }

      addRouters.value = filterRoutersList
      menus.value = filterMenusByVisible(filterRoutersList)
      const dynamicRoutes = generateRoutes(filterRoutersList)
      dynamicRoutes.forEach((route) => {
        router.addRoute(route as RouteRecordRaw)
      })
      return true
    }
    catch (error) {
      console.error('添加路由失败:', error)
      const appStore = useAppStoreWithOut()
      appStore.loginLoading = false
      return false
    }
  }

  const handleResetRouter = () => {
    try {
      addRouters.value.forEach((route) => {
        route.menuName && router.removeRoute(route.menuName)
      })
      router.removeRoute('_BaseRoot')
      router.removeRoute('404Page')
      resetMenuState()
    }
    catch (error) {
      console.error('重置路由失败:', error)
    }
  }

  return {
    handleAddRouter,
    handleResetRouter,
  }
}
